{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.\n",
      "It can be downloaded at https://aka.ms/vs/16/release/vc_redist.x64.exe\n"
     ]
    }
   ],
   "source": [
    "import torch  \n",
    "import torch.nn as nn \n",
    "import torch.optim as optim  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "数据准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建输入数据和目标数据  \n",
    "x = torch.randn(100, 1)  \n",
    "y = 3 * x + 2 + torch.randn(100, 1)  # 真实参数为3和2  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "权重初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 模型参数  \n",
    "w = torch.randn(1, requires_grad=True)  \n",
    "b = torch.randn(1, requires_grad=True)  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 优化器  \n",
    "optimizer = optim.SGD([w, b], lr=0.01)  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Tensor"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0, Loss: 23.513072967529297\n",
      "Epoch 100, Loss: 1.2674400806427002\n",
      "Epoch 200, Loss: 1.191766619682312\n",
      "Epoch 300, Loss: 1.1913740634918213\n",
      "Epoch 400, Loss: 1.1913669109344482\n",
      "Epoch 500, Loss: 1.1913666725158691\n",
      "Epoch 600, Loss: 1.1913665533065796\n",
      "Epoch 700, Loss: 1.1913666725158691\n",
      "Epoch 800, Loss: 1.1913666725158691\n",
      "Epoch 900, Loss: 1.1913666725158691\n"
     ]
    }
   ],
   "source": [
    "# 训练模型\n",
    "for epoch in range(1000):\n",
    "    model = x * w + b\n",
    "    loss = ((model - y) ** 2).mean()\n",
    "\n",
    "    optimizer.zero_grad()\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "\n",
    "    if epoch % 100 == 0:\n",
    "        print(f\"Epoch {epoch}, Loss: {loss.item()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Learned parameters: w = 3.0206804275512695, b = 2.045978307723999\n"
     ]
    }
   ],
   "source": [
    "print(f'Learned parameters: w = {w.item()}, b = {b.item()}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用Torch.nn的方式重写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义模型\n",
    "class LinearRegressionModel(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(LinearRegressionModel, self).__init__()\n",
    "        self.linear = nn.Linear(1, 1)  # 输入和输出特征的数量都为1\n",
    "\n",
    "    def forward(self, x):\n",
    "        return self.linear(x)\n",
    "\n",
    "\n",
    "# 创建模型实例\n",
    "model = LinearRegressionModel()\n",
    "\n",
    "# 创建输入数据和目标数据\n",
    "x = torch.randn(100, 1)\n",
    "y = 3 * x + 2 + torch.randn(100, 1)\n",
    "\n",
    "# 定义损失函数\n",
    "criterion = nn.MSELoss()\n",
    "\n",
    "# 定义优化器\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)\n",
    "\n",
    "# 训练模型\n",
    "for epoch in range(1000):\n",
    "    # 前向传播：计算预测值和损失\n",
    "    y_pred = model(x)\n",
    "    loss = criterion(y_pred, y)\n",
    "\n",
    "    # 反向传播：计算梯度\n",
    "    optimizer.zero_grad()\n",
    "    loss.backward()\n",
    "\n",
    "    # 更新参数\n",
    "    optimizer.step()\n",
    "\n",
    "    # 打印损失（可选）\n",
    "    if epoch % 100 == 0:\n",
    "        print(f\"Epoch {epoch}, Loss: {loss.item()}\")\n",
    "\n",
    "# 获取训练后的参数\n",
    "w, b = model.parameters()\n",
    "print(f\"Learned parameters: w = {w.item()}, b = {b.item()}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "my_env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
